const { ApiResponse } = require('@shared/utils/response');
const logger = require('@shared/utils/logger');
const path = require('path');
const fs = require('fs');

class UploadController {
  constructor() {
    this.uploadImage = this.uploadImage.bind(this);
    this.uploadFile = this.uploadFile.bind(this);
  }

  /**
   * 上传图片
   */
  async uploadImage(req, res) {
    try {
      logger.debug('接收到图片上传请求');
      logger.debug('请求体:', req.body);
      logger.debug('请求文件:', req.file);
      
      if (!req.file) {
        logger.warn('未接收到上传的图片文件');
        return res.json(ApiResponse.error('请选择要上传的图片'));
      }

      // 获取文件信息
      const file = req.file;
      const originalName = file.originalname;
      const fileName = file.filename;
      const fileSize = file.size;
      const mimeType = file.mimetype;

      // 构建访问URL
      const baseUrl = process.env.NODE_ENV === 'production'
        ? process.env.API_BASE_URL || 'https://api.example.com'
        : `http://localhost:${process.env.PORT || 3001}`;

      const filePath = `/public/uploads/images/${fileName}`;
      const fileUrl = `${baseUrl}${filePath}`;

      logger.info(`图片上传成功: ${fileName}, 大小: ${fileSize} 字节`);

      // 返回上传结果
      return res.json(ApiResponse.success({
        url: fileUrl,
        path: filePath,
        name: originalName,
        size: fileSize,
        type: mimeType
      }));
    } catch (error) {
      logger.error('图片上传失败:', error);
      return res.json(ApiResponse.error(error.message || '图片上传失败'));
    }
  }

  /**
   * 上传文件
   */
  async uploadFile(req, res) {
    try {
      if (!req.file) {
        return res.json(ApiResponse.error('请选择要上传的文件'));
      }

      // 获取文件信息
      const file = req.file;
      const originalName = file.originalname;
      const fileName = file.filename;
      const fileSize = file.size;
      const mimeType = file.mimetype;

      // 构建访问URL
      const baseUrl = process.env.NODE_ENV === 'production'
        ? process.env.API_BASE_URL || 'https://api.example.com'
        : `http://localhost:${process.env.PORT || 3001}`;

      const filePath = `/public/uploads/files/${fileName}`;
      const fileUrl = `${baseUrl}${filePath}`;

      logger.info(`文件上传成功: ${fileName}, 大小: ${fileSize} 字节`);

      // 返回上传结果
      return res.json(ApiResponse.success({
        url: fileUrl,
        path: filePath,
        name: originalName,
        size: fileSize,
        type: mimeType
      }));
    } catch (error) {
      logger.error('文件上传失败:', error);
      return res.json(ApiResponse.error(error.message || '文件上传失败'));
    }
  }
}

module.exports = new UploadController(); 